/*
 * @Author: fanjs
 * @Date: 2025-03-12 10:52:34
 * @Description: 任务列表选择
 */
import React, { useEffect, useState, useCallback } from 'react';
import {
  Drawer,
  DrawerContent,
  DrawerHeader,
  DrawerBody,
  Button,
  DrawerFooter,
  Radio,
  RadioGroup,
  Tooltip,
  addToast,
  cn,
  Chip
} from "@heroui/react";
import { fetchTaskListApi } from '@/service/api/email'
import { useNavigate } from 'react-router-dom';
interface TaskDrawerEmits {
  task_id: string | undefined;
  submit: (taskInfo: any | null) => void;
  isOpen: boolean;
}
export const CustomRadio = ({ data, value }: any) => {

  // 定义状态类型
  type TaskStatus = "draft" | "ready" | "sending" | "completed" | "partially_completed" | "failed";

  // 状态颜色映射
  const statusColorMap: Record<TaskStatus, string> = {
    draft: "default",
    ready: "success",
    sending: "warning",
    completed: "secondary",
    partially_completed: "warning",
    failed: "danger",
  };

  // 状态名称映射
  const statusNameMap: Record<TaskStatus, string> = {
    draft: "草稿",
    ready: "待发送",
    sending: "发送中",
    completed: "已完成",
    partially_completed: "部分完成",
    failed: "发送失败",
  };

  // 获取状态颜色的函数
  const formatStatus = (status: string, isName?: boolean): any => {
    if (isName) return statusNameMap[status as TaskStatus]
    else return statusColorMap[status as TaskStatus] || "default"; // 默认颜色
  };

  return (
    <Radio
      classNames={{
        base: cn(
          "w-full bg-content1 m-0",
          "hover:bg-default-50",
          "cursor-pointer rounded-lg p-3 border-1 border-default-200",
          "data-[selected=true]:border-secondary",
        ),
      }}
      color='secondary'
      value={value}
    >
      <div className="w-[340px]">
        <div className='flex items-center mb-1'>
          <span className='text-sm font-semibold text-default-800'>
            <Chip color={formatStatus(data.status)} size="sm" className='mr-1 h-5 rounded-[4px]' variant="flat">
              {formatStatus(data.status, true)}
            </Chip>
            {data.subject}
          </span>
        </div>
        <div className="text-tiny text-default-400 mb-0.5">
          包含变量：
          {data.variables.map((item: any, index: number) => (
            <span key={index} className='px-1 text-primary'>{item}</span>
          ))}
        </div>
        <div className="text-tiny text-default-400 mb-0.5">最近更新：{data.updated_at}</div>
        <div className='flex gap-3'>
          <div className="text-tiny text-default-400">
            共计 <span className='text-primary'>{data.total_count}</span> 封邮件
          </div>
          <div className="text-tiny text-default-400">
            成功 <span className='text-primary'>{data.sent_count}</span> 封
          </div>
          <div className="text-tiny text-default-400">
            失败 <span className='text-danger'>{data.failed_count}</span> 封
          </div>
        </div>
      </div>
    </Radio>
  );
};

const TaskDrawer: React.FC<TaskDrawerEmits> = ({ task_id, submit, isOpen }) => {
  const [taskList, setTaskList] = useState<any[]>([])
  const [selectedTask, setSelectedTask] = useState<any>('');
  const navigate = useNavigate();

  // 提交
  const handleSelect = () => {
    if (!selectedTask) return addToast({ title: '先选择一条任务信息' })
    const row = taskList.find((item) => item.id === selectedTask)
    if (row.status !== 'draft') return addToast({ title: '此任务不是草稿状态，无法编辑' })
    submit(row);
  }

  // 去配置收件人
  const handleToRecipients = () => {
    if (!selectedTask) return addToast({ title: '先选择一条任务信息' })

    navigate(`/distribute/recipients/${selectedTask}`)
  }

  // 关闭
  const handleClose = () => {
    submit(null);
    setSelectedTask(null)
  }

  // 展示时获取任务列表
  const fetchTaskList = useCallback(async () => {
    try {
      const { data }: any = await fetchTaskListApi({ page: 1, pageSize: 200 })
      setTaskList(data.list)
    } catch {
      addToast({ title: '获取任务列表失败!!' })
    }
  }, []);

  useEffect(() => {
    if (!isOpen) return;
    fetchTaskList();
    if (task_id) setSelectedTask(task_id);
  }, [isOpen, task_id, fetchTaskList]);

  return (
    <>
      <Drawer
        hideCloseButton
        backdrop="blur"
        classNames={{
          backdrop: "z-40",
          base: "data-[placement=right]:sm:m-2 data-[placement=left]:sm:m-2 rounded-medium",
        }}
        className='z-0'
        isOpen={isOpen}
      >
        <DrawerContent>
          <>
            <DrawerHeader className="items-center absolute top-0 inset-x-0 z-50 flex flex-row gap-2 px-2 py-2 border-b border-default-200/50 bg-content1/50 backdrop-saturate-150 backdrop-blur-lg">
              <Tooltip content="收起弹窗">
                <Button
                  isIconOnly
                  className="text-default-600"
                  size="sm"
                  variant="light"
                  onPress={handleClose}
                >
                  <svg
                    fill="none"
                    height="20"
                    stroke="currentColor"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth="2"
                    viewBox="0 0 24 24"
                    width="20"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path d="m13 17 5-5-5-5M6 17l5-5-5-5" />
                  </svg>
                </Button>
              </Tooltip>
              <span className="text-[15px]">
                选择历史任务
              </span>
            </DrawerHeader>
            <DrawerBody className="pt-16">
              {(!taskList || taskList.length < 1) && (
                <div className="flex flex-col items-center justify-center h-full">
                  <span className="text-default-400">暂无数据</span>
                </div>
              )}

              <RadioGroup
                classNames={{ base: "w-full" }}
                onValueChange={setSelectedTask}
                value={selectedTask}
              >
                {taskList && taskList.length > 0 && taskList.map((item) => (
                  <CustomRadio
                    data={item}
                    value={item.id}
                  >
                  </CustomRadio>
                ))}
              </RadioGroup>
            </DrawerBody>
            <DrawerFooter className='flex justify-start border-t border-default-100 py-3 px-4 gap-x-3'>
              {taskList && taskList.length > 0 && <Button variant="solid" color="secondary" onPress={handleToRecipients}>配置收件人</Button>}
              {taskList && taskList.length > 0 && <Button variant="solid" color="secondary" onPress={handleSelect}>编辑任务</Button>}
              <Button variant="flat" color="secondary" onPress={handleClose}>取 消</Button>
            </DrawerFooter>
          </>
        </DrawerContent>
      </Drawer>
    </>
  );
}

export default TaskDrawer;
